package logic

import (
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/core/utils"
	"context"
	"errors"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type EmailCodeSendRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewEmailCodeSendRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EmailCodeSendRegisterLogic {
	return &EmailCodeSendRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *EmailCodeSendRegisterLogic) EmailCodeSendRegister(req *types.MailCodeSendRequest) (resp *types.MailCodeSendResponse, err error) {
	//邮箱不存在才能用邮箱注册
	var count int64
	err = l.svcCtx.DbConn.Table("user_basic").Where("email=?", req.Email).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		return nil, errors.New("邮箱已存在")
	}
	code := utils.RandCode()
	//存储验证码
	l.svcCtx.RedisClient.Set(l.ctx, req.Email, code, time.Second*time.Duration(utils.EmailCodeExpire))
	//发送验证码
	err = utils.MailSendCode(req.Email, code)
	return
}
